/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// 等待设备就绪
document.addEventListener('deviceready', function() {
    console.log('设备就绪，翻译功能可用');
}, false);

// 语言名称映射
const languageNames = {
    'auto': '自动检测',
    'zh': '中文',
    'en': '英语',
    'yue': '粤语',
    'wyw': '文言文',
    'jp': '日语',
    'kor': '韩语',
    'fra': '法语',
    'spa': '西班牙语',
    'th': '泰语',
    'ara': '阿拉伯语',
    'ru': '俄语',
    'pt': '葡萄牙语',
    'de': '德语',
    'it': '意大利语',
    'el': '希腊语',
    'nl': '荷兰语',
    'pl': '波兰语',
    'bul': '保加利亚语',
    'est': '爱沙尼亚语',
    'dan': '丹麦语',
    'fin': '芬兰语',
    'cs': '捷克语',
    'rom': '罗马尼亚语',
    'slo': '斯洛文尼亚语',
    'swe': '瑞典语',
    'hu': '匈牙利语',
    'cht': '繁体中文',
    'vie': '越南语'
};

// 表单提交处理
document.getElementById('translate-form').addEventListener('submit', function(e) {
    e.preventDefault();
    translateText();
});

// 翻译文本
function translateText() {
    const submitBtn = document.getElementById('submit-btn');
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const resultContainer = document.getElementById('result-container');
    
    // 获取表单数据
    const formData = {
        token: document.getElementById('token').value.trim(),
        q: document.getElementById('text').value.trim(),
        from: document.getElementById('from').value,
        to: document.getElementById('to').value
    };
    
    // 验证文本
    if (!formData.q) {
        showError('请输入要翻译的文本');
        return;
    }
    
    // 验证token
    if (!formData.token) {
        showError('请输入API Token');
        return;
    }
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.textContent = '翻译中...';
    loading.classList.add('show');
    errorMessage.classList.remove('show');
    resultContainer.classList.remove('show');
    
    // 构建请求参数
    const params = new URLSearchParams();
    params.append('token', formData.token);
    params.append('q', formData.q);
    params.append('from', formData.from);
    params.append('to', formData.to);
    
    // 发送POST请求
    fetch('https://v3.alapi.cn/api/fanyi', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('API响应:', data);
        
        if (data.success && data.code === 200) {
            displayTranslation(data.data);
        } else {
            showError(data.message || '翻译失败，请检查参数');
        }
    })
    .catch(error => {
        console.error('请求错误:', error);
        showError('请求失败: ' + error.message + '。请检查网络连接或API Token是否正确');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = '翻译';
        loading.classList.remove('show');
    });
}

// 显示错误信息
function showError(message) {
    const errorMessage = document.getElementById('error-message');
    errorMessage.textContent = message;
    errorMessage.classList.add('show');
}

// 显示翻译结果
function displayTranslation(data) {
    const resultContainer = document.getElementById('result-container');
    const sourceText = document.getElementById('source-text');
    const targetText = document.getElementById('target-text');
    const fromLang = document.getElementById('from-lang');
    const toLang = document.getElementById('to-lang');
    
    // 显示原文
    if (data.src) {
        sourceText.textContent = data.src;
    } else {
        sourceText.textContent = '无原文';
    }
    
    // 显示译文
    if (data.dst) {
        targetText.textContent = data.dst;
    } else {
        targetText.textContent = '无译文';
    }
    
    // 显示语言信息
    if (data.from) {
        fromLang.textContent = languageNames[data.from] || data.from;
    } else {
        fromLang.textContent = '未知';
    }
    
    if (data.to) {
        toLang.textContent = languageNames[data.to] || data.to;
    } else {
        toLang.textContent = '未知';
    }
    
    // 显示结果容器
    resultContainer.classList.add('show');
    
    // 滚动到结果区域
    resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 尝试从本地存储加载token
    const savedToken = localStorage.getItem('translate_api_token');
    if (savedToken) {
        document.getElementById('token').value = savedToken;
    }
    
    // 保存token到本地存储
    document.getElementById('token').addEventListener('blur', function() {
        const token = this.value.trim();
        if (token) {
            localStorage.setItem('translate_api_token', token);
        }
    });
    
    console.log('翻译页面加载完成');
});

